package com.wzc.pet.service.impl;

import com.wzc.basic.exception.BusinessException;
import com.wzc.basic.service.IBaiduAiAuditService;
import com.wzc.basic.service.impl.BaseServiceImpl;
import com.wzc.basic.util.CodeGenerateUtils;
import com.wzc.basic.util.DistanceUtils;
import com.wzc.basic.util.PageList;
import com.wzc.basic.util.Point;
import com.wzc.order.domain.OrderPetAcquisition;
import com.wzc.order.mapper.OrderPetAcquisitionMapper;
import com.wzc.org.domain.Employee;
import com.wzc.org.domain.Shop;
import com.wzc.org.mapper.EmployeeMapper;
import com.wzc.org.mapper.ShopMapper;
import com.wzc.pet.domain.Pet;
import com.wzc.pet.domain.SearchMasterMsg;
import com.wzc.pet.domain.SearchMasterMsgAuditLog;
import com.wzc.pet.dto.AcceptDto;
import com.wzc.pet.mapper.PetMapper;
import com.wzc.pet.mapper.SearchMasterMsgAuditLogMapper;
import com.wzc.pet.mapper.SearchMasterMsgMapper;
import com.wzc.pet.query.SearchMasterMsgQuery;
import com.wzc.pet.service.ISearchMasterMsgService;
import com.wzc.user.domain.User;
import com.wzc.user.mapper.UserMapper;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.Date;

@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private IBaiduAiAuditService baiduAiAuditService;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;
    @Autowired
    private PetMapper petMapper;


    @Override
    public void publish(SearchMasterMsg smm, Long id) {
        // 通过 logininfo_id 查询当前用户信息
        User user = userMapper.loadByLogininfoId(id);
        // 将用户信息赋值到ssm
        smm.setUser_id(user.getId());
        smm.setNote("待审核！");
        // 调用工具类获取当前用户地址坐标
        Point point = DistanceUtils.getPoint(smm.getAddress());
        // 再调用工具计算出距离用户最近的店铺（shop_id）
        Shop nearestShop = DistanceUtils.getNearestShop(point, shopMapper.loadAll());
        smm.setShop_id(nearestShop.getId()); // 获取店铺id
        // 将寻主消息保存到数据库中
        searchMasterMsgMapper.save(smm);

        // 审核文本
        Boolean textBoolean = baiduAiAuditService.textAudit(smm.getTitle() + smm.getName() + smm.getAddress() + smm.getCoatColor());
        // 审核图片
        Boolean imgBoolean = baiduAiAuditService.imageAudit(smm.getResources());
        if(textBoolean && imgBoolean){
            // 审核通过 1. 修改状态
            smm.setState(1);
            smm.setNote("待处理！");
            searchMasterMsgMapper.update(smm);
            // 2. 添加审核日志
            SearchMasterMsgAuditLog smmal= new SearchMasterMsgAuditLog();
            smmal.setMsg_id(smm.getId());
            smmal.setState(1);
            smmal.setAudit_time(new Date());
            smmal.setNote("待处理状态！");
            // 保存审核日志信息
            searchMasterMsgAuditLogMapper.save(smmal);
        } else { // 审核失败
            // 审核不通过 1. 修改状态
            smm.setNote("审核没通过！");
            searchMasterMsgMapper.update(smm);
            // 2. 添加审核日志
            SearchMasterMsgAuditLog smmal= new SearchMasterMsgAuditLog();
            smmal.setMsg_id(smm.getId());
            smmal.setState(0);
            smmal.setAudit_time(new Date());
            smmal.setNote("审核没通过！");
            // 保存审核日志信息
            searchMasterMsgAuditLogMapper.save(smmal);
            throw new BusinessException("信息异常，请重新输入");

        }
    }

    @Override
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, Long id) {
        // 通过logininfoId 查询empl0yee
        Employee emp = employeeMapper.loadByLogininfoId(id);
        query.setState(1);
        if(emp.getShop_id() != null){
           query.setShopId(emp.getShop_id());
        }
        return super.queryPage(query);
    }

//    @Override
//    public PageList<SearchMasterMsg> user(SearchMasterMsgQuery query, Long id) {
//        User user = userMapper.loadByLogininfoId(id);
//        query.setUserId(user.getId());
//        return super.queryPage(query);
//    }

    @Override
    public void reject(Long id) {
        searchMasterMsgMapper.reject(id);
    }

    @Override
    public void accept(AcceptDto dto, Long id) throws Exception{
        // 获取页面传入的参数
        Long handler = dto.getHandler();
        Long msgId = dto.getMsgId();
        String note = dto.getNote();
        // 根据 寻主订单 msgId 查询 t_order_pet_acquisition 订单信息
        OrderPetAcquisition order = orderPetAcquisitionMapper.loadBySmmId(msgId);
        if(order != null){ // != null  表示订单信息已存在（已接单）
            throw new BusinessException("订单正在处理中！");
        } else {
            // 如果为空，则说明第一次接单，接单是要生成一个pet信息和一个支付订单
            // 1. 生成一个pet,  根据寻主信息 SearchMasterMsg 对应生成
            SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.loadById(msgId);
            Pet pet = searchMasterMsg2Pet(searchMasterMsg); // 调用方法生成pet
            petMapper.save(pet); // 将pet保存到数据库

            // 获取生产者对象
            DefaultMQProducer producer = new DefaultMQProducer("order_producer_group");
            // 设置nameserver地址
            producer.setNamesrvAddr("localhost:9876");

            // 生成一个 收购订单
            OrderPetAcquisition opa = inorderPetAcquisition(dto,pet,searchMasterMsg);
            orderPetAcquisitionMapper.save(opa); // 保存订单信息

            // 启动producer
            producer.start();
            Message message = new Message("order", "order", "订单生成中!".getBytes(StandardCharsets.UTF_8));
            message.setDelayTimeLevel(3);
            producer.send(message);
        }

    }

    private OrderPetAcquisition inorderPetAcquisition(AcceptDto dto, Pet pet, SearchMasterMsg smm) {
        OrderPetAcquisition order = new OrderPetAcquisition(); // 创建订单对象
        // 调用工具类生成有个订单编号
        String orderSn = CodeGenerateUtils.generateOrderSn(smm.getUser_id());
        order.setOrderSn(orderSn); // 将生成的订单编号赋值到order
        order.setDigest("【" + smm.getTitle() + "】"); // 设置摘要
        // 设置订单过期时间
        order.setLastcomfirmtime(new Date(System.currentTimeMillis() + 2*24*60*60*1000));
        order.setState(0);
        order.setPet_id(pet.getId());
        order.setPrice(smm.getPrice());
        order.setUser_id(smm.getUser_id());
        order.setShop_id(smm.getShop_id());
        order.setAddress(smm.getAddress());
        order.setEmp_id(dto.getHandler());
        order.setSearch_master_msg_id(dto.getMsgId());
        return order;
    }

    /**
     * 通过 寻主信息 SearchMasterMsg 生成一个pet
     * @param smm
     * @return
     */
    private Pet searchMasterMsg2Pet(SearchMasterMsg smm) {
        Pet pet = new Pet(); // 创建pet对象
        // 将寻主信息中的宠物信息复制到pet
        pet.setName(smm.getName());
        pet.setCostprice(smm.getPrice());
        pet.setType_id(smm.getPetType());
        pet.setResources(smm.getResources());
        pet.setShop_id(smm.getShop_id());
        pet.setUser_id(smm.getUser_id());
        return pet;
    }
}
